package top.infopub.security.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import top.infopub.security.core.CaptchaUsernamePasswordToken;
import top.infopub.security.service.SysStaffOfficeService;
import top.infopub.security.service.SysUserService;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.DateUtil;
import top.infopub.util.SpringContext;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static top.infopub.security.util.TokenMD5Utils.pwdMD5;

public class SsoFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        if(httpRequest.getRequestURI().indexOf("/mgr/sso")>-1){
            String param = request.getParameter("backUrl");
            String backUrl = param.substring(0, param.lastIndexOf("?"));
            String tmpParam = param.substring(param.lastIndexOf("?") + 1);
            if (StringUtils.isNotBlank(tmpParam)) {
                String[] strArr = tmpParam.split("=");
                if (strArr != null && strArr.length == 2) {
                    if (StringUtils.equals("zninv", strArr[0])) {
                        String zninv = strArr[1];
                        AuthorizationVO userByCode = SpringContext.getBean(SysUserService.class).getUserByCode(zninv);
                        CaptchaUsernamePasswordToken m = new CaptchaUsernamePasswordToken(userByCode.getUserName(), userByCode.getPassword(), false, "sso", null,
                                "sso");
                        getSubject(request, response).login(m);
                        SessionUserUtils.setSessionAttributeForUserDtl(userByCode);
                        System.out.println("backUrl:" + backUrl);
                        SpringContext.getBean(SysStaffOfficeService.class).setDefaultOrgDept();
                        WebUtils.issueRedirect(request, response, backUrl, null, true);
                        return true;
                    }
                }
            }
        }
        final String token=((HttpServletRequest) request).getParameter("token");
        if(StringUtils.isNotEmpty(token)&&httpRequest.getRequestURI().indexOf("/mgr/sso")>-1){
            String[] s = token.split("_");
            if(s.length!=2){
                redirectToLogin(request, response);
                return false;
            }
            String userCode=s[0];
            String day = DateUtil.timeStamp2Date(String.valueOf(System.currentTimeMillis()), "yyyy-MM-dd");
            String pwd=s[1];
            String znjtPwd="";
            if(StringUtils.isNotEmpty(day)){
                znjtPwd = pwdMD5("znjt", userCode,day);
            }else{
                znjtPwd = pwdMD5("znjt", userCode);
            }

            if(!znjtPwd.equalsIgnoreCase(pwd)){
                redirectToLogin(request, response);
                return false;
            }
            AuthorizationVO userByCode = SpringContext.getBean(SysUserService.class).getUserByCode(userCode);
            CaptchaUsernamePasswordToken m =new CaptchaUsernamePasswordToken(userByCode.getUserName(), userByCode.getPassword(), false, "sso", null,
                    "sso");
            getSubject(request,response).login(m);
            SessionUserUtils.setSessionAttributeForUserDtl(userByCode);
            SpringContext.getBean(SysStaffOfficeService.class).setDefaultOrgDept();
            String backUrl = request.getParameter("backUrl");
            String queryString = ((HttpServletRequest) request).getQueryString();
            if (queryString.indexOf("&") >= 0) {
                queryString = queryString.substring(queryString.indexOf("&"));
            }
            backUrl = backUrl + queryString;
            System.out.println("backUrl:"+backUrl);
            WebUtils.issueRedirect(request, response, backUrl,null,true);
            return true;
        }else{
            return false;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }
}
